package com.qf.kele02.intercepto;

import com.qf.kele02.entity.User;
import com.qf.kele02.service.UserSevice;
import com.qf.kele02.utils.Constants;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Data
public class AutoLoginInterceptor implements HandlerInterceptor {

	@Qualifier(value="userServicePlusImp")
	@Autowired
	private UserSevice userService;

	@Override
	public boolean preHandle( HttpServletRequest request,HttpServletResponse response,Object handler ) throws Exception {


		//1.判断，如果session中有user对象了，那么直接重定向到/plateform.html
		HttpSession session=request.getSession( );

		User sessionUser=(User) session.getAttribute( "user" );

		if(sessionUser!=null) {
			log.debug( "用户已经登录过了，直接重定向到首页！" );
			response.sendRedirect( "/plateform.html" );
			return false;
		}

		//2.检查请求中是否有userToken cookie，有的话还愿用户的登录状态
		Cookie[] cookies=request.getCookies( );

		if(cookies!=null && cookies.length>0) {
			for(Cookie cookie: cookies) {
				String name=cookie.getName( );
				if(name.equals( Constants.USER_TOKEN )) {
					String userTokenValue=cookie.getValue( );
					String[] usernameAndmd5Password=userTokenValue.split( "-" );
					String username=usernameAndmd5Password[0];
					String md5Password=usernameAndmd5Password[1];

					//返还用户登录状态
					User user=userService.restoreUser( username,md5Password );

					//把user对象放入session域中
					session.setAttribute( "user",user );

					//重定向到plateform.html
					log.debug( "根据cookie还原用户登录状态成功，user={}",user );
					response.sendRedirect( "/plateform.html" );
					return false;

				}
			}
		}
		log.debug( "没有免登录需要的cookie，进入登录页面" );
		return true;

	}
}